package clientserver;

import java.io.IOException;

import vcp.client.GUI.mvc.model.UIRootModel;
import vcp.client.exceptions.EmptyRequestException;
import vcp.client.interfaces.IObserver;
import vcp.client.request.Request;
import vcp.client.request.response.ResponseRefresh;
import vcp.client.request.response.ResponseRequest;
import vcp.client.request.response.ResponseTimeChange;

/**
 * 
 * @author VCP team
 * 
 *         <p>
 *         This class is responsible for providing client services, but acts as
 *         a dummy client. client performs busy wait each time send a request to
 *         server
 *         </p>
 */
public class DummyUIRootModel extends UIRootModel
{
	private final Object lock;
	private ResponseRequest response;

	public ResponseRequest getResponse()
	{
		ResponseRequest responseRequest = null;

		synchronized (this.lock)
		{
			responseRequest = this.response;
		}
		return responseRequest;
	}

	public void setResponse(ResponseRequest response)
	{
		synchronized (this.lock)
		{
			this.response = response;
		}
	}

	public DummyUIRootModel()
	{
		this.lock = new Object();
	}

	@Override
	protected synchronized void handleMessageFromServer(Object msg)
	{
		System.out.println(msg);
		if (!(msg instanceof ResponseTimeChange))
		{
			if (!(msg instanceof ResponseRefresh))
			{
				if ((msg instanceof ResponseRequest))
				{
					System.out.println(msg.toString());
					this.setResponse((ResponseRequest) msg);
				}
			}
		}
	}

	@Override
	public void registerAndSendRequest(Request request, IObserver observer) throws EmptyRequestException, IOException
	{
		this.response = null;
		this.sendToServer(request);
	}

	/**
	 * Perform busy wait till response received back from {@link DummyServer}
	 */
	public void waitForResponse()
	{
		while (this.getResponse() == null)
		{
			try
			{
				Thread.sleep(500);
			}
			catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println();
		}
	}
}
